package com.leeh.jsontest;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.leeh.jsontest.Constents.URL_OURSELVES_CAMPUS_LIST;
import static com.leeh.jsontest.Constents.URL_OURSELVES_OPTION_COURSE;
import static com.leeh.jsontest.Constents.URL_OURSELVES_OPTION_VALIDATE;
import static com.leeh.jsontest.Constents.URL_OURSELVES_TERM_LIST;

/**
 * Created by Liheng on 2017-04-16.
 */

public class FreeOptionFragment extends Fragment {

    private Handler handler;

    private ImageView imgVerCode;
    private EditText txtVerCode;
    private TextView txtNetwork;
    private Spinner spCampus;
    private Spinner spTerm;
    private Button btnSearch;
    private LinearLayout verCodeLinearLayout;
    private CourseViewTwo courseViewTwo;
    private ProgressBar pbLoading;

    private SpinnerAdapter campusAdapter = null;
    private List<SpinnerContent> campusList = null;

    private SpinnerAdapter termAdapter = null;
    private List<SpinnerContent> termList = null;

    private MySqliteHelper helper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_free_option, container, false);
        AsynchronousTask();
        initView(view);
        initData();
        initEvents();

        return view;
    }


    /**
     * 更新UI
     */
    public void AsynchronousTask() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case Constents.GET_VERCODER: {
                        pbLoading.setVisibility(View.GONE);
                        byte[] imageByte = msg.getData().getByteArray("verCode");
                        Bitmap image = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
                        imgVerCode.setImageBitmap(image);
                        break;
                    }
                    case Constents.GET_COURSE: {
                        handleGetCourseInfo((String) msg.obj);
                        break;
                    }
                    case Constents.GET_SPINNER_CONTENT: {
                        handleSpinnerContent((String) msg.obj, msg.arg1);
                        break;
                    }
                    case Constents.GET_DISABLE_NETWORK: {
                        txtNetwork.setVisibility(View.VISIBLE);
                        break;
                    }
                }
            }
        };
    }

    /**
     * 处理获取到的课表信息
     *
     * @param html
     */
    private void handleGetCourseInfo(String html) {
        if (DataParse.parseCheckVerCode(html)) {
            List<String> courseData = DataParse.parseCourse(html);
            StringBuilder course = new StringBuilder();
            if (courseData.size() == 0) {
                course.append("没有课程");
            } else {
                String termKey = termList.get(spTerm.getSelectedItemPosition()).getKey();
                String campusKey = campusList.get(spCampus.getSelectedItemPosition()).getKey();
                DBManager.insertIntoOptionalTable(helper.openDatabase(), termKey, campusKey, html);
            }
            courseViewTwo.setData(courseData);
            //txtCourse.setText(course.toString());
            courseViewTwo.setVisibility(View.VISIBLE);
            verCodeLinearLayout.setVisibility(View.GONE);
            pbLoading.setVisibility(View.GONE);
        } else {
            if (verCodeLinearLayout.getVisibility() == View.VISIBLE) {
                Toast.makeText(getActivity(), "验证码输入错误!", Toast.LENGTH_LONG).show();
            }
            DataUtils.getVerCode(handler, URL_OURSELVES_OPTION_VALIDATE);
            verCodeLinearLayout.setVisibility(View.VISIBLE);
            pbLoading.setVisibility(View.VISIBLE);
            courseViewTwo.setVisibility(View.GONE);
            txtVerCode.setText("");

        }
    }

    /**
     * 处理下拉框内容
     *
     * @param html
     */
    private void handleSpinnerContent(String html, int type) {
        switch (type) {
            case 40: {
                campusList = DataParse.parseSpinnerFromJsonToList(html, "campus");
                campusAdapter.addAll(campusList);
                DBManager.insertIntoCampus(helper.openDatabase(), campusList);
                break;
            }
            case 41: {
                termList = DataParse.parseSpinnerFromJsonToList(html, "term");
                termAdapter.addAll(termList);
                DBManager.insertIntoTerm(helper.openDatabase(), termList);
                Log.i("term", "handleSpinnerContent: " + termList.size());
                break;
            }
        }

    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        imgVerCode = (ImageView) view.findViewById(R.id.verCode_image);
        txtVerCode = (EditText) view.findViewById(R.id.verCode_text);
        txtNetwork = (TextView) view.findViewById(R.id.network_connection_textView);
        courseViewTwo = (CourseViewTwo) view.findViewById(R.id.course_table_courseViewTwo);
        spCampus = (Spinner) view.findViewById(R.id.campus_spinner);
        spTerm = (Spinner) view.findViewById(R.id.term_spinner);
        btnSearch = (Button) view.findViewById(R.id.search_button);
        verCodeLinearLayout = (LinearLayout) view.findViewById(R.id.verCode_linearLayout);
        pbLoading = (ProgressBar) view.findViewById(R.id.loading_progressBar);
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        imgVerCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataUtils.getVerCode(handler, URL_OURSELVES_OPTION_VALIDATE);
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtNetwork.setVisibility(View.GONE);
                if (spCampus.getSelectedItemPosition() == -1 ||
                        campusList.get(spCampus.getSelectedItemPosition()).getKey().equals("")) {
                    Toast.makeText(getActivity(), "请选择校区!", Toast.LENGTH_LONG).show();
                } else {
                    boolean isExist = searchFromDatabaseCourse();
                    if (!isExist) {
                        //verCodeLinearLayout.setVisibility(View.GONE);
                        courseViewTwo.setVisibility(View.GONE);
                        pbLoading.setVisibility(View.VISIBLE);
                        Map<String, String> dataParams = new HashMap<String, String>();
                        dataParams.put("Sel_XNXQ", termList.get(spTerm.getSelectedItemPosition()).getKey());
                        dataParams.put("Sel_XQXX", campusList.get(spCampus.getSelectedItemPosition()).getKey());
                        dataParams.put("txt_yzm", txtVerCode.getText().toString().trim());

                        DataUtils.searchFromNetworkCourse(handler, URL_OURSELVES_OPTION_COURSE, dataParams);

                        txtVerCode.setText("");
                    }
                }
            }
        });

        txtNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (android.os.Build.VERSION.SDK_INT > 13) {
                        startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                    } else {
                        startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        helper = MySqliteHelper.getInstance(getActivity());

        termList = DBManager.getTermSpinnerContent(helper.openDatabase());
        if (termList.size() == 0) {
            DataUtils.getOptionInfoFromNetWork(handler, URL_OURSELVES_TERM_LIST, 41);
        }
        campusList = DBManager.getCampusSpinnerContent(helper.openDatabase());
        if (campusList.size() == 0) {
            DataUtils.getOptionInfoFromNetWork(handler, URL_OURSELVES_CAMPUS_LIST, 40);
        }
        campusAdapter = new SpinnerAdapter(getActivity(), R.layout.spinner_content, campusList);
        campusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCampus.setAdapter(campusAdapter);

        termAdapter = new SpinnerAdapter(getActivity(), R.layout.spinner_content, termList);
        termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spTerm.setAdapter(termAdapter);
    }

    /**
     * 从数据库去数据
     */
    public boolean searchFromDatabaseCourse() {
        String termKey = termList.get(spTerm.getSelectedItemPosition()).getKey();
        String campusKey = campusList.get(spCampus.getSelectedItemPosition()).getKey();
        String html = DBManager.optionalTableQuery(helper.openDatabase(), termKey, campusKey);
        if (html.equals("")) {
            return false;
        }
        List<String> courseData = DataParse.parseCourse(html);
        Log.i("lllllll", "searchFromDatabaseCourse: " + courseData.size());
        courseViewTwo.setData(courseData);
        courseViewTwo.setVisibility(View.VISIBLE);
        //txtCourse.setText(course.toString());
        return true;
    }

}
